<template>
  <!-- 操作栏 -->
  <el-row justify="end">
    <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['house:sku:create']">
      <Icon icon="ep:plus" class="mr-5px" /> 新增
    </el-button>
  </el-row>

  <!-- 列表 -->
  <ContentWrap class="mt-10px">
    <el-table
      ref="contactRef"
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column label="房产名称" align="center" prop="name" />
      <el-table-column label="旧面积m²" align="center" prop="oldArea" />
      <el-table-column label="新面积m²" align="center" prop="area" />
      <el-table-column label="销售状态" align="center" prop="saleStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_INVESTMENT_NATURE" :value="scope.row.saleStatus" />
        </template>
      </el-table-column>
      <el-table-column label="是否使用新面积" align="center" prop="useNewArea">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.useNewArea" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.HOUSE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['house:sku:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['house:sku:update']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <ContentWrap class="mt-10px">
    <el-table v-loading="loading" :data="areaList">
      <el-table-column class-name="sum" label="旧面积汇总数值" align="center" prop="sumOldArea" />
      <el-table-column class-name="sum" label="新面积汇总数值" align="center" prop="sumNewArea" />
      <el-table-column class-name="sum" label="新旧面积合计" align="center" prop="sumTotalArea" />
    </el-table>
  </ContentWrap>
  <!-- 表单弹窗：添加 -->
  <HouseSkuForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import * as HouseSpuApi from '@/api/house/house/spu'
import HouseSkuForm from './HouseSkuForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import { BizTypeEnum } from '@/api/crm/permission'
import { h } from 'vue'
import Decimal from 'decimal.js'
import { text } from 'stream/consumers'
import { color } from 'echarts'

defineOptions({ name: 'OperationList' })
const props = defineProps<{
  bizType: number // 业务类型
  bizId: number // 业务编号
  customerId?: number // 特殊：客户编号
}>()

const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const areaList = ref([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: undefined,
  date: [],
  operationManager: undefined,
  businessStatus: undefined,
  industryCategory: undefined,
  otherSituations: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const message = useMessage()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 置空参数
    queryParams.customerId = undefined
    // 执行查询
    let data = { list: [], total: 0 }
    switch (props.bizType) {
      case BizTypeEnum.CRM_CUSTOMER:
        queryParams.customerId = props.bizId
        data = await HouseSpuApi.getSkuPage(queryParams)
        await HouseSpuApi.getSkuAreaPage(queryParams).then((res) => {
          areaList.value = res
        })

        break
      default:
        return
    }
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, props.bizId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await HouseSpuApi.deleteSkuCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 获取列表的合计 */
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: any[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = h('div', { style: { fontWeight: 'bold' } }, ['合计'])
      return
    }
    if (index === 3 || index === 4 || index === 5) {
      sums[index] = ''
      return
    }
    const values = data.map((item: any) => Number(item[column.property]))
    if (!values.every((value: any) => isNaN(value))) {
      sums[index] = h('div', { style: { fontWeight: 'bold' } }, [
        values.reduce((prev: any, curr: any) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return new Decimal(prev).plus(curr).toNumber()
          } else {
            return prev
          }
        }, 0)
      ])
    } else {
      sums[index] = ''
    }
  })
  return sums
}

/** 监听打开的 bizId + bizType，从而加载最新的列表 */
watch(
  () => [props.bizId, props.bizType],
  () => {
    handleQuery()
  },
  { immediate: true, deep: true }
)
</script>
<style lang="scss" scoped>
:deep(.sum > .cell) {
  font-weight: bold;
}
</style>
